<?php

namespace Remoteshell\PhpBotSdk\public;

class Router {
    private $routes = [];

    public function addRoute($method, $uri, $controller, $action) {
        $this->routes[] = [
            'method' => $method,
            'uri' => $uri,
            'controller' => $controller,
            'action' => $action
        ];
    }

    public function dispatch() {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // 处理带查询参数的URI
        $method = $_SERVER['REQUEST_METHOD'];

        foreach ($this->routes as $route) {
            if ($route['method'] === $method) {
                // 生成正则表达式模式
                $pattern = '#^' . preg_replace('/{(\w+)}/', '(?P<$1>[^/]+)', $route['uri']) . '$#';

                if (preg_match($pattern, $uri, $matches)) {
                    $params = array_values(array_filter($matches, 'is_int', ARRAY_FILTER_USE_KEY));
                    array_shift($params); // 移除完整匹配项（索引0）

                    $controller = new $route['controller'];
                    $action = $route['action'];
                    call_user_func_array([$controller, $action], $params);
                    return;
                }
            }
        }

        echo "404 Not Found";
    }

}
